<template>
    <div class="root">
        <!--选择面片-->
        <div :tabindex="0"
             class="dialog-query-list"
             :class="[(!params.queryListActiveMap.meshList && params.meshList.length === 0) ? 'list-warn': ((!params.queryListActiveMap.meshList && params.meshList.length > 0) || params.lockedProperty.meshList) ? 'list-normal': '']"
             >
<!--            @click="switchActive()"-->
            <div style="display: flex;justify-content: space-between;align-items: center">
                <div class="query-description" style="flex-grow: 1"
                     :class="[params.meshList.length === 0 ? 'description-enlarge': '']">
                    {{ $t('message.ConvertGridToHookface.cmd.selectTips') }}
                    {{ params.lockedProperty.meshList ? $t('message.Common.unchangeable') : '' }}
                    <div v-if="sortable && params.meshList.length" class="move-buttons">
                        <i class="moveUpItemCl" @click="moveUpItem"/>
                        <i class="moveDownItemCl" @click="moveDownItem"/>
                    </div>
                    <div v-if="!sortable && !params.meshList.length && !selectable"
                         class="img-slot-wrapper">
                        <slot name="imgContent"></slot>
                    </div>
                </div>
<!--                <i v-if="(params.meshList.length > 1 && !locked) || (params.meshList.length > 0 && false)"-->
<!--                   style=" font-family: 'Font Awesome 5 Free';content: '\f014';display: inline-block;font-size: inherit;line-height: 1;text-transform: none;vertical-align: middle;cursor: pointer"-->
<!--                   @click="removeAllItem"></i>-->
            </div>

            <div tabindex="-1" :id="scrollId" class="scroll-list">
                <ul class="text-color8">
                    <li tabindex="0"
                        :key="item.id"
                        v-for="(item,index) in params.meshList"
                        v-on:focus="highlight(item)"
                        v-on:blur="removeHighlight(item)"
                        v-on:mouseenter="highlight(item)"
                        v-on:mouseleave="removeHighlight(item)"
                        @click="selectItem(index, item)"
                        @keyup.enter="selectItem(index,item)"
                        class="query-item"
                        :class="
                            [{'selected-query-li' : selectedItem && selectedItem.id === item.id},
                            {'list-highlight-li' : highlightItem(item)},
                            {'remove-u-v-input-li' : inputUVParams(item)}]">
                            <span v-if="!inputUVParams(item)" style="display: flex;align-items: center;overflow: hidden">
                                <span v-if="showListImg" class="item-img-wrap">
                                  <img v-if="item.img" :src="item.img" alt=""/>
                                </span>
                                <span class="text-ellipsis" :title="$t(item.name)">{{ $t(item.name) }}</span>
                            </span>
                                <!--孔命令中的面上点输入框-->
                                <span v-else class="inputUVParams">
                                    <dialog-u-v-input
                                            :list="params.meshList"
                                            :opened="true"
                                            :item="item"
                                            :index="index"
                                            @valueChanged="handleChange"/>
                                </span>
                                <span
                                        :class="[{'remove-u-v-input' : inputUVParams(item)}, {'removeIcon': !inputUVParams(item)}]"
                                        v-if="!locked"
                                        @click.stop="removeItem(index,item)">&times;</span>
                    </li>
                </ul>
            </div>
        </div>

        <!--曲面类型-->
        <div class="dialog-row mt-3">
            <label :style="{ margin: 2 + 'px'}">{{ $t('message.ConvertGridToHookface.cmd.surfaceType') }}</label>
            <div class="image-allowed-button-list">
                <div v-for="(img, index) in imgList"
                     :key="img.name"
                     class="image-button">
                    <div @click="changeSurfaceType(img)" :class="['image-allowed-button',{'image-allowed-button-selected': img.name === params.surfaceType},
                      {'image-allowed-button-no-selected': img.name !== params.surfaceType}]">
                        <img :src="img.src" class="img-button" :alt="img.title"/>
                    </div>
                </div>
            </div>
        </div>
        <!--公差精度-->
        <div class="collapse-panel">
            <div class="collapse-a">
                <div>
                    <p><b>{{ $t('message.ConvertGridToHookface.cmd.tolerance') }}</b></p>
                </div>
                <div :id="collapseId" @click="foldClick">
                    <span class="cursor-pointer" :class="[{'cursor-pointer': !disabled}]">
                        <i :class="['fa', collapse ? 'fa-angle-up' : 'fa-angle-down']"/>
                    </span>
                </div>
            </div>

            <div v-show="!collapse">
                <div class="meshRange">
                    <label :style="{ margin: 2 + 'px'}">{{ $t('message.ConvertGridToHookface.cmd.higher') }}</label>
                    <input type="range"
                           v-model="params.tolerance"
                           :min="params.range.min"
                           :max="params.range.max"
                           :step="params.range.step"
                           @change="clearPreview"/>
                    <label :style="{ margin: 2 + 'px'}">{{ $t('message.ConvertGridToHookface.cmd.lower') }}</label>
                </div>
            </div>
        </div>
        <!--计算-->
        <div class="dialog-row mt-3" style="justify-content: center!important;">
            <el-button size="small"
                       type="info"
                       :disabled="!allowClick"
                       @click="calculate"
                       :loading="params.calculating">
                <slot v-if="calculating" name="calculating">{{
                    $t('message.ConvertGridToHookface.cmd.calculating')
                    }}
                </slot>
                <slot v-else name="calculate">{{ $t('message.ConvertGridToHookface.cmd.calculate') }}</slot>
            </el-button>
        </div>
        <!--按钮 组-->
        <div class="footer" style="height: 50px;">
            <div class="dialog-footer">
                <el-button ref="applyButton"
                           type="primary"
                           :disabled="!allowClick"
                           @click="goApply"
                           @keyup.enter.native="goApply">
                    {{ $t(message.Common.apply) }}
                </el-button>
                <el-button ref="confirmButton"
                           type="primary"
                           :disabled="!allowClick"
                           @click="goConfirm"
                           @keyup.enter.native="goConfirm">
                    {{ $t(message.Common.confirm) }}
                </el-button>
                <el-button ref="closeButton"
                           :disabled="false"
                           @click="goClose"
                           @keyup.enter.native="goClose">
                    {{ $t(message.Common.close) }}
                </el-button>
                <!--                <el-button ref="cancelButton"-->
                <!--                           :disabled="disabledCancel"-->
                <!--                           @click="goCancel"-->
                <!--                           @keyup.enter.native="goCancel">-->
                <!--                    {{ $t(message.Common.cancel) }}-->
                <!--                </el-button>-->
            </div>
        </div>
    </div>
</template>

<script>
import {convertGridToHookfaceCmd} from "../../Command/ConvertGridToHookfaceCommand";
import {SurfaceType} from "../../modeling/TypeDefine";
import {getCommonPic} from "../js/util/GetCommonPic";
import InputVariable from "../../util/InputVariable";
import DialogMixin from "./DialogMixin";
import {TR_ch as message} from "../../util/languages/ch";
import {eventBus} from "../../eventbus/eventbus";

let IdCount = 0;
export default {
    mixins: [DialogMixin],
    name: "ConvertGridToHookface",
    watch: {
        'opened': {
            handler() {
                this.collapse = this.opened;
            }
        }
    },

    data() {
        IdCount++;
        return {
            //属性初始化
            disabled: false,
            opened: false,
            collapseId: 'dialogCollapsed' + IdCount,
            collapse: this.opened,
            tolerance: new InputVariable(0.001),
            //绑定曲面类型
            imgList: [
                {
                    name: SurfaceType.PLANE,
                    src: getCommonPic('平面.svg', 'hookfaceTypes'),
                    title: this.$t("message.ConvertGridToHookface.cmd.plane"),
                },
                {
                    name: SurfaceType.SPHERE,
                    src: getCommonPic('球面.svg', 'hookfaceTypes'),
                    title: this.$t("message.ConvertGridToHookface.cmd.sphere"),
                },
                {
                    name: SurfaceType.CYLINDER,
                    src: getCommonPic('圆柱面.svg', 'hookfaceTypes'),
                    title: this.$t("message.ConvertGridToHookface.cmd.cylinder"),
                },
                // {
                //   name: SurfaceType.CONE,
                //   src: getCommonPic('圆锥面.svg', 'meshDesignIcon'),
                //   title: this.$t("message.ConvertGridToHookface.cmd.cone")
                // },
            ],
            //参数
            params: {
                meshList: [],//拾取三角面片列表
                queryListActiveMap: {
                    meshList: 1,
                },
                lockedProperty: {
                    meshList: false,
                },
                meshId: 0,
                surfaceType: SurfaceType.PLANE, // 曲面类型
                tolerance: 5,
                range: {  // 公差精度范围
                    min: 0,
                    max: 10,
                    step: 1,
                },
                calculating: false, // 是否在计算中
            },
            scrollId: "dialogList" + IdCount,
            selectedItem: null, //TODO
            highlightElementId: null,  //TODO
            // active: false,
            locked: false,
            sortable: false,
            selectable: false,
            dialogQueryListElId: 'dialogQueryList' + IdCount,
        };
    },

    mounted() {
        convertGridToHookfaceCmd.init(400, 250, 500, () => {

            this.changePluginContainerHeight();
            convertGridToHookfaceCmd.pickTriangleMesh((element) => {
                if(!element)  return;
                // 不能同时拾取不同网格上的三角面片
                if (this.params.meshId !== 0 && element.id !== this.params.meshId) {
                    return;
                }
                let ele = JSON.parse(element);
                this.params.meshId = ele.meshId;
            });

            convertGridToHookfaceCmd.addSelected((meshInfo) =>{
                if(!meshInfo) return;
                let mesh = JSON.parse(meshInfo);
                let index = this.params.meshList.findIndex(info => {
                    return info.id === mesh.id;
                })
                if (index > -1) {
                    this.params.meshList.splice(index, 1); //若已选中，需移除
                } else {
                    this.params.meshList.push(mesh);
                }
                if (this.params.meshList.length === 0) {
                    this.params.meshId = 0;
                }
                this.clearPreview();
            });

            // convertGridToHookfaceCmd.removeSelected((index) =>{
            //     if (index === -1) {
            //         this.removeAllItem();
            //     } else {
            //         this.removeItem(index, this.params.meshList[index]);
            //     }
            // });

            // if (this.defaultChecked && this.params.meshList.length > 0) {
            //     this.selectedItem = null;
            //     this.selectItem(0,this.params.meshList[0]);
            // }

            //TODO
            // convertGridToHookfaceCmd.addHighlight((info) =>{
            //     if(!info) return;
            //     this.highlightElementId = info?.element?.id;
            //     // instance不存在，将this.instanceId赋值为''，与info.instanceId赋值保持一致，避免highlightItem方法中的比较出错
            //     this.instanceId = info?.instance?.id ?? '';
            // });

            //TODO
            // convertGridToHookfaceCmd.scrollToCurrent((elementInfo) =>{
            //     if (elementInfo) {
            //         let ele = document.getElementById(elementInfo.name);
            //         if (ele) {
            //             const container = document.querySelector(`#${this.scrollId}`);
            //             container.scrollTo({
            //                 top: ele.offsetTop,
            //                 behavior: "smooth"
            //             });
            //         }
            //     }
            // });
        });
    },

    computed: {
        message() {
            return message;
        },
        allowClick() {
            return this.params.meshList.length > 0 && !this.params.calculating;
        },
        showListImg() {
            return this.params.meshList.find(item => item.img);
        }
    },

    methods: {
        //改变 UI高度
        changePluginContainerHeight() {
            convertGridToHookfaceCmd.changePluginContainerHeight(
                {minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight + 20})
        },
        //切换曲面类型
        changeSurfaceType(img) {
            if (this.params.surfaceType === img.name) {
                return;
            }
            this.params.surfaceType = img.name;
            this.clearPreview();
        },
        //根据索引移除列表中的面片
        removeItem(index,item) {
            convertGridToHookfaceCmd.removeItemByIndex(index);
            if (this.defaultChecked) {
                this.selectedItem = this.selectedItem?.index === item.index ? null : this.selectedItem;
            }
            if (!this.locked) {
                this.params.meshList.splice(index, 1);
               // this.switchActive();
                $('#' + this.dialogQueryListElId).focus();
                this.clearPreview();
                if (this.params.meshList.length === 0) {
                    this.params.meshId = 0;
                }

                //TODO 移除高亮
                // viewEffectManager.clearHighlights();
                // outlineHelper.clearHighlight();
                // scene.render();

                // this.$emit("removeItem", item, index);
                // this.$emit("removeHighlight", item);
                //this.closeTip();
            }
        },
        //控制折叠展开
        foldClick() {
            if (this.disabled) {
                return;
            }
            this.collapse = !this.collapse;
        },
        //计算
        calculate() {
            this.params.calculating = true;
            let config = this.getCommandParams(true);
            convertGridToHookfaceCmd.previewMesh(config,res =>{
                this.params.calculating = false;
            });
            this.params.calculating = false;
        },
        //应用
        goApply(...args) {
            this.goConfirm(...args);
        },
        //确定
        goConfirm(...args) {
            let config = this.getCommandParams(false);
            convertGridToHookfaceCmd.createMesh(config, modelObj => {
                //debugger;
            });
            this.goClose(); //关闭对话框
        },
        //关闭
        goClose() {
            convertGridToHookfaceCmd.closeActiveCmd();
        },
        //清除预览
        clearPreview() {
            convertGridToHookfaceCmd.clearPreview();
        },
        //组织发送命令时的数据
        getCommandParams(isPreview = false){
            let meshId = this.params.meshId;
            let face = this.params.meshList.map(info => {
                let faceArr  = info.id.split(',');
                return [faceArr[1], faceArr[2], faceArr[3]]
            });
            let surfaceType = this.params.surfaceType;
            let tolerance = this.params.tolerance;
            return {
                meshId, face, surfaceType, tolerance
            }
        },
        //高亮列表中选中的面片
        highlight(item) {
            if(!item) return;
            convertGridToHookfaceCmd.highlightItem(item);
        },
        removeHighlight(item) {
          convertGridToHookfaceCmd.clearAllHighlight();
        },

        inputUVParams(item) {
            return item.geometryId; //这里产品也是undefined,不知道为何返回这个东西
        },

        selectItem(index, item) {
           // debugger;
            if (this.sortable || this.selectable) {
                this.selectedItem = item;
                this.selectedItem.index = index;
            }
        },
        highlightItem(item) {
            return (
                this.highlightElementId === item.id
                && this.instanceId === item.instanceId
            )
        },
        handleChange(index) {
            this.$emit("valueChanged", index);
        },
        moveUpItem() {
            if (this.selectedItem) {
                if (this.selectedItem.index > 0) {
                    this.params.meshList.splice(this.selectedItem.index, 1);
                    this.params.meshList.splice(this.selectedItem.index - 1, 0, this.selectedItem);
                    this.selectedItem.index -= 1;
                }
            }
        },
        moveDownItem() {
            if (this.selectedItem) {
                if (this.selectedItem.index < this.list.length - 1) {
                    this.params.meshList.splice(this.selectedItem.index, 1);
                    this.params.meshList.splice(this.selectedItem.index + 1, 0, this.selectedItem);
                    this.selectedItem.index += 1;
                }
            }
        },

    },

    destroyed() {
        if (this.highlightCbId) {
            eventBus.off('addHighlightElement', this.highlightCbId);
        }
        if (this.scrollToCbId) {
            eventBus.off('scrollToElementAtQueryList', this.scrollToCbId);
        }
        eventBus.off('syncRemoveItem');
    }

}
</script>

<style scoped>
.root {
    font-size: var(--text-12);
}

.dialog-row {
    margin: 7px 0;
    display: flex;
    height: 26px;
    align-items: center;
}

.dialog-query-list {
    padding: .25rem .25rem .25rem .5rem;
    margin: .5rem 0 .25rem;
    position: relative;
    border-radius: .2rem;
    background-color: #d6eaff;
    color: var(--text-color5);
    border: 1px solid #6e7177;
    cursor: pointer;
}

.image-allowed-button-list {
    display: flex;
    margin: 5px 4px;
    flex-wrap: wrap;
}

.image-allowed-button {
    background-color: var(--bg-color8);
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    border-radius: 3px;
    opacity: .7;
}

.image-allowed-button:hover,
.image-allowed-button-selected {
    opacity: 1;
    background-color: var(--bg-color23);
    cursor: pointer;
}

.image-allowed-button-no-selected:hover,
.image-allowed-button-no-selected {
    opacity: 0.6;
//cursor: not-allowed; background-color: unset; cursor: pointer;
}

.img-button {
    width: 24px;
    height: 24px;
}

.image-button {
    margin: 3px 5px;
}

.collapse-panel > .collapse-a {
    color: var(--text-color1);
    margin: 5px 0;
}

.meshRange {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
    align-items: center;
}

.meshRange input[type=range] {
    -webkit-appearance: none;
    height: 3px;
    border: 0px;
    background: #43464a;
    outline: none;
}

.collapse-a {
    display: flex;
    justify-content: space-between;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 12px;
    padding-bottom: 12px;
    padding-left: 0.5rem;
    padding-right: 0.5rem;
}

.query-description {
    line-height: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    transition: .3s;
}

.scroll-list {
    overflow: auto;
    position: relative;
    max-height: 150px;
    outline: none;
    padding-right: .25rem;
}

.dialog-query-list ul {
    font-size: 12px;
    opacity: .95;
}

.query-description {
    line-height: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    transition: .3s;
}

.dialog-query-list .img-slot-wrapper {
    box-shadow: 2px 2px 2px var(--bg-color3);
    transform: translateY(0);
    transition: all .3s;
    color: var(--text-color1);
    font-size: var(--text-12);
    cursor: pointer;
    align-items: flex-start;
    display: flex;
}

.dialog-query-list .img-slot-wrapper:hover {
    transform: translateY(2px);
    box-shadow: 1px 2px 2px #0070b159;
}

.list-warn .img-slot-wrapper {
    box-shadow: 2px 2px 2px var(--bg-color8);
}

.list-warn .img-slot-wrapper:hover {
    transform: translateY(2px);
    box-shadow: 1px 2px 2px #99caff21;
}

.dialog-query-list .move-buttons {
    margin-right: 35px;
}

.description-enlarge {
    font-size: inherit;
}

.dialog-query-list .query-item {
    min-height: 24px;
    cursor: pointer;
    padding: .25rem .5rem;
    margin: .25rem;
    align-items: center;
    justify-content: space-between;
    display: flex;
    border-radius: .2rem;
}

.moveUpItemCl {
    font-family: 'Font Awesome 5 Free';
    content: "\f062";
    display: inline-block;
    font-size: inherit;
    line-height: 1;
    text-transform: none;
    vertical-align: middle;
    cursor: pointer;
    padding-right: 0;
}

.moveDownItemCl {
    font-family: 'Font Awesome 5 Free';
    content: "\f063";
    display: inline-block;
    font-size: inherit;
    line-height: 1;
    text-transform: none;
    vertical-align: middle;
    cursor: pointer;
}

.selected-query-li {
    background: rgba(0, 0, 0, .15);
}

.remove-u-v-input-li {
    position: relative;
}

.removeIcon {
    cursor: pointer;
    margin-left: .5rem;
}

.removeIcon:hover {
    color: firebrick;
}
</style>